package com.woniu.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.woniu.domain.Stu;
import com.woniu.service.StuService;
import com.woniu.service.impl.StuServiceImpl;
import com.woniu.utils.MyBeanUtils;

/**
 * Servlet implementation class AddStuServlet
 */
@WebServlet("/AddStuServlet")
public class AddStuServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddStuServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String,String[]> parameterMap = request.getParameterMap();
		try {		
			Stu stu = MyBeanUtils.populate(Stu.class, parameterMap);
			String[] hobbies = request.getParameterValues("sHobby");
			String sHobby = Arrays.toString(hobbies).substring(1,Arrays.toString(hobbies).length()-1);
			stu.setsHobby(sHobby);
			//将数据传到Service
			StuService ss = new StuServiceImpl();
			boolean result = false;
			try {
				result = ss.saveStu(stu);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(result) {
				request.getRequestDispatcher("GoStuListServlet").forward(request, response);
			}else {
				request.getRequestDispatcher("addStu.jsp").forward(request, response);
			}
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
